package com.buaa.aimall.userModule.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.buaa.aimall.Utils.Client.BUAAOAuth2Client;
import com.buaa.aimall.Utils.BaseResponse;
import com.buaa.aimall.Utils.Config.AliyunIdentifyAuthConfig;
import com.buaa.aimall.Utils.Enum.StatusCode;
import com.buaa.aimall.Utils.HttpUtils;
import com.buaa.aimall.Utils.PrivacyUtils;
import com.buaa.aimall.userModule.Converter.UserConvert;
import com.buaa.aimall.userModule.DTO.IdentityAuthenticationDTO;
import com.buaa.aimall.userModule.DTO.RegisterDTO;
import com.buaa.aimall.userModule.Entity.UserEntity;
import com.buaa.aimall.userModule.Service.UserService;
import com.buaa.aimall.userModule.VO.UserVO;
import jakarta.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    UserService userService;

    @Resource
    private StringEncryptor stringEncryptor;

    private final AliyunIdentifyAuthConfig aliyunIdentifyAuthConfig;

    private final BUAAOAuth2Client buaaOAuth2Client;

    @Autowired
    public AuthController(AliyunIdentifyAuthConfig aliyunIdentifyAuthConfig, BUAAOAuth2Client buaaOAuth2Client) {
        this.aliyunIdentifyAuthConfig = aliyunIdentifyAuthConfig;
        this.buaaOAuth2Client = buaaOAuth2Client;
    }

    @PostMapping("/register")
    public BaseResponse<UserVO> register(@RequestBody RegisterDTO registerDTO) {
        UserEntity userEntity = UserConvert.INSTANCE.registerDTOToEntity(registerDTO);
        if (userService.getUserByUsername(userEntity.getUsername()) != null) {
            return new BaseResponse<>(StatusCode.USERNAME_ALREADY_EXIST, "用户名已存在", null);
        }
        userEntity.setPassword(passwordEncoder.encode(userEntity.getPassword()));
        userEntity.setBalance(0);
        userEntity.setIncome(0);
        userService.save(userEntity);
        return new BaseResponse<>(StatusCode.SUCCESS, "注册成功", UserConvert.INSTANCE.userEntityToVO(userEntity));
    }

    @PostMapping("/idcard-check")
    public BaseResponse<JSONObject> identityAuthentication(@RequestBody IdentityAuthenticationDTO identityAuthenticationDTO) {
        UserEntity user = userService.getCurrentUser();

        if (StringUtils.isNotBlank(user.getName())) {
            return new BaseResponse<>(StatusCode.VERIFIED_WITH_REAL_NAME, "当前用户已完成实名认证", null);
        }

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + aliyunIdentifyAuthConfig.getAppcode());

        Map<String, String> querys = new HashMap<String, String>();
        querys.put("name", identityAuthenticationDTO.getName());
        querys.put("idcard", identityAuthenticationDTO.getIdcard());

        try {
            HttpResponse response = HttpUtils.doGet(aliyunIdentifyAuthConfig.getHost(), aliyunIdentifyAuthConfig.getPath(), "GET", headers, querys);
            JSONObject responseBody = JSON.parseObject(EntityUtils.toString(response.getEntity()));

            if (responseBody.getInteger("code") == 400) {
                return new BaseResponse<>(StatusCode.PARAM_ERROR, "请输入有效的身份证号码", responseBody);
            }
            if (responseBody.getInteger("code") == 200 && responseBody.getJSONObject("data").getInteger("result") == 1) {
                return new BaseResponse<>(StatusCode.INCONSISTENT_NAME_IDCARD, "姓名与身份证号不一致", responseBody);
            }

            if (responseBody.getInteger("code") == 200 && responseBody.getJSONObject("data").getInteger("result") == 0) {
                user.setName(stringEncryptor.encrypt(identityAuthenticationDTO.getName()));
                user.setIdcard(stringEncryptor.encrypt(identityAuthenticationDTO.getIdcard()));
                userService.updateById(user);
                return new BaseResponse<>(StatusCode.SUCCESS, "实名认证成功", responseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BaseResponse<>(StatusCode.SUCCESS, "认证失败", null);
    }

    @GetMapping("/idcard-get")
    public BaseResponse<JSONObject> identityAuthenticationGet() {
        UserEntity user = userService.getCurrentUser();

        if (StringUtils.isBlank(user.getName())) {
            return new BaseResponse<>(StatusCode.NO_REAL_NAME_AUTH, "当前用户未完成实名认证", null);
        }

        JSONObject responseBody = new JSONObject();
        responseBody.put("name", PrivacyUtils.maskName(stringEncryptor.decrypt(user.getName())));
        responseBody.put("idcard", PrivacyUtils.maskIdCard(stringEncryptor.decrypt(user.getIdcard())));
        return new BaseResponse<>(StatusCode.SUCCESS, "获取实名认证信息成功", responseBody);
    }

    @PostMapping("/buaa-compute-login")
    public BaseResponse<String> oauthRefreshToken() {
        UserEntity user = userService.getCurrentUser();

        var userId = user.getId();
        var response = buaaOAuth2Client.login(userId);
        var token = JSONObject.parseObject(response.getBody()).getString("data");

        return new BaseResponse<>(StatusCode.SUCCESS, "获取token测试成功", token);
    }
}
